import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-02-09
 * Time: 14:52
 */
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new ArrayList<Integer>();
        List<Integer> list = new ArrayList<>();
        int l = 0 , r = matrix[0].length-1 , u = 0 , d = matrix.length-1;
        while(true){
            for(int i = l ; i <= r ; i++){
                list.add(matrix[u][i]);
            }
            if(++u > d) break;
            for(int i = u ; i <= d ; i++){
                list.add(matrix[i][r]);
            }
            if(--r < l) break;
            for(int i = r ; i >= l ; i--){
                list.add(matrix[d][i]);
            }
            if(--d < u) break;
            for(int i = d ; i >= u ; i--){
                list.add(matrix[i][l]);
            }
            if(++l > r) break;
        }
        return list;
    }

}


public class Test9 {
}
